package game.http;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.swiftpass.config.SwiftpassConfig;
import com.swiftpass.util.SignUtils;
import com.swiftpass.util.XmlUtils;

import game.module.payment.logic.PaymentManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import lion.http.HttpHtmlHandler;
import sdk.common.HttpClientUtils;

public class SwiftpassHttpHandler extends HttpHtmlHandler {

	private static Logger logger = LoggerFactory.getLogger(SwiftpassHttpHandler.class);

	public SwiftpassHttpHandler(String name) {
		super(name);
	}

	@Override
	public String strHttpHandle(ChannelHandlerContext ctx, FullHttpRequest request, String resString) throws Exception {
		return preOrder(resString);
	}

	private static String preOrder(String resString) {
		try {
			logger.info("swiftpass http callback：{}", resString);
			String respString = "fail";
			if (resString != null && !"".equals(resString)) {
				Map<String, String> map = XmlUtils.toMap(resString, "utf-8");
				if (map.containsKey("sign")) {
					if (!SignUtils.checkParam(map, SwiftpassConfig.key)) {
						respString = "fail";
					} else {
						String status = map.get("status");
						if (status != null && "0".equals(status)) {
							String result_code = map.get("result_code");
							if (result_code != null && "0".equals(result_code)) {
								// 此处可以在添加相关处理业务，校验通知参数中的商户订单号out_trade_no和金额total_fee是否和商户业务系统的单号和金额是否一致，一致后方可更新数据库表中的记录。
								logger.info("pay success!");
								String orderId = map.get("out_trade_no");
								int ptotal_fee = Integer.valueOf(map.get("total_fee"));
								return PaymentManager.getInstance().swiftpassCallNotify(orderId, ptotal_fee);
							}
						}
						respString = "success";
					}
				}
				return respString;
			}
		} catch (Exception e) {
			logger.error("", e);
		}
		return "fail";
	}

	public static void main(String[] args) throws Exception {
		String resString = "<xml><attach><![CDATA[254]]></attach>\n<bank_type><![CDATA[ICBC_DEBIT]]></bank_type>\r\n<charset><![CDATA[UTF-8]]></charset><device_info><![CDATA[AND_SDK]]></device_info><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[N]]></is_subscribe><mch_id><![CDATA[101590024668]]></mch_id><nonce_str><![CDATA[1505745103931]]></nonce_str><openid><![CDATA[op-exw4iN9DjIkQOW3FyYCc_WKAQ]]></openid><out_trade_no><![CDATA[1437015911829504]]></out_trade_no><out_transaction_id><![CDATA[4200000030201709182900364118]]></out_transaction_id><pay_result><![CDATA[0]]></pay_result><result_code><![CDATA[0]]></result_code><sign><![CDATA[F0B08A7467F98F1A85C9A1C7FA857BD6]]></sign><sign_type><![CDATA[MD5]]></sign_type><status><![CDATA[0]]></status><time_end><![CDATA[20170918223143]]></time_end><total_fee><![CDATA[6800]]></total_fee><trade_type><![CDATA[pay.weixin.wappay]]></trade_type><transaction_id><![CDATA[101590024668201709185238058446]]></transaction_id><version><![CDATA[2.0]]></version></xml>";
		SwiftpassConfig.key = "5775f2452ebd720d747e6984fcda8009";
		System.out.println(preOrder(resString));

	}

	public static void main2(String[] args) {
		Map<String, Object> requestObj = new HashMap<>();
		requestObj.put("module", "pay");
		requestObj.put("player_id", 5655);
		requestObj.put("trade_type", "pay.weixin.app");
		requestObj.put("transaction_id", RandomStringUtils.randomAlphanumeric(32));
		requestObj.put("total_fee", 32800);
		requestObj.put("diamond", 560);
		ObjectMapper objectMapper = new ObjectMapper();
		String requestParams;
		try {
			String agentServerUrl = "http://192.168.0.145:9090/GuanQuWeb/api/agent";
			logger.info("query start");
			requestParams = objectMapper.writeValueAsString(requestObj);
			long s1 = System.currentTimeMillis();
			Map<String, Object> respObj = HttpClientUtils.getInstance().doHttpPost(agentServerUrl, requestParams);
			logger.info("cost={}", System.currentTimeMillis() - s1);
			int ret = (Integer) respObj.get("result");
			logger.info("ret={}", ret);
		} catch (JsonProcessingException e) {
			logger.error("", e);
		}
		System.out.println(System.currentTimeMillis());
	}

}
